package com.ruoyi.web.controller.app;

import com.ruoyi.common.utils.PageUtils;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.web.exception.RRException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.common.FilesUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("app/dynamic")
@Api("朋友圈接口")
public class ForAppDynamicController extends BaseController {

    @Autowired
    private IAppDynamicService dynamicService;
    @Autowired
    private IAppDynamicCommentService commentService;
    @Autowired
    private IAppDynamicLikeService likeService;
    @Autowired
    private IAppDynamicTimelineService timelineService;
    @Autowired
    private IAppUserService userService;
    @Autowired
    private IAppUserRelationService userRelationService;
    @Autowired
    private IAppDynamicMsgService iAppDynamicMsgService;

    @PostMapping("getDynamicPage")
    @ApiOperation("获取朋友圈动态分页")
    public AjaxResult getDynamicPage(@ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
                                     @ApiParam("条数") @RequestParam(defaultValue = "6") Integer limit) {
//        Long userId = getUserId();
//        // 用户与好友设置的朋友圈权限
//        List<Long> friendIdList = userRelationService.getFriendIds(userId);
//        friendIdList.add(userId);
//
//        QueryWrapper<AppDynamic> queryWrapper = Wrappers.query();
//        queryWrapper.in("user_id", userId);
//        Page<AppDynamic> obj = dynamicService.page(new Page<>(page, limit), queryWrapper);
//
//        List<AppDynamic> list = obj.getRecords();
//        for (AppDynamic info : list) {
//            info.setContent(CommonUtils.decodeNickname(info.getContent()));
//        }
//        Map<String, Object> ret = new HashMap<>();
//
//        ret.put("totalPage", obj.getPages());
//        ret.put("totalCount", obj.getSize());
//        ret.put("dynamicList", list);
//        return AjaxResult.ok(0, "", ret);


        Map<String, Object> ret = new HashMap<>();
        // 获取时间轴分页
        QueryWrapper<AppDynamicTimeline> timelineWrapper = new QueryWrapper<>();
        timelineWrapper.eq("user_id", getUserId());
        timelineWrapper.orderByDesc("crt_time");
        Page timelinePage = timelineService.page(new Page<>(page, limit), timelineWrapper);

        /*
         * 获取好友idList
         */
        QueryWrapper<AppUserRelation> relationWrapper = new QueryWrapper<>();
        // 用户与好友设置的朋友圈权限
        relationWrapper.eq("user_id", getUserId());
        relationWrapper.eq("self_state", 0);
        relationWrapper.eq("self_is_be_looked", 0);
        relationWrapper.eq("other_state", 0);
        relationWrapper.eq("other_is_look", 0);
        List<Long> friendIdList = userRelationService.getFriendIdToTimeLine(relationWrapper);
        friendIdList.add(getUserId());

        /*
         * 获取分页对应动态详情
         */
        List<AppDynamicTimeline> noReadTimelineList = Lists.newArrayList();
        List<AppDynamic> dynamicList = Lists.newArrayList();
        AppDynamic dynamicEntity;
        AppDynamicTimeline timelineEntity;
        List<AppDynamicLike> likeList;
        List<AppDynamicComment> commentList;
        for (int i = 0; i < timelinePage.getRecords().size(); i++) {
            timelineEntity = (AppDynamicTimeline) timelinePage.getRecords().get(i);
            if (timelineEntity.getIsRead() == 0) {
                timelineEntity.setIsRead(1);
                noReadTimelineList.add(timelineEntity);
            }

            dynamicEntity = dynamicService.getById(timelineEntity.getDynamicId());
            dynamicEntity.setUserName(dynamicEntity.getUserName());
            dynamicEntity.setContent(CommonUtils.decodeNickname(dynamicEntity.getContent()));
            // 当前用户是否点赞
            dynamicEntity.setIsLike(0);
            if (dynamicEntity.getLikeCount() > 0) {
                // 获取点赞列表
                QueryWrapper<AppDynamicLike> likeWrapper = new QueryWrapper<>();
                likeWrapper.eq("dynamic_id", dynamicEntity.getId());
                likeWrapper.in("user_id", friendIdList);
                likeWrapper.orderByAsc("crt_time");
                likeList = likeService.list(likeWrapper);
                for (AppDynamicLike likeEntity : likeList) {
                    likeEntity.setUserName(likeEntity.getUserName());
                    if (likeEntity.getUserId().equals(getUserId())) dynamicEntity.setIsLike(1);
                }
                dynamicEntity.setLikeList(likeList);
            }
            if (dynamicEntity.getCommentCount() > 0) {
                // 获取评论列表
                QueryWrapper<AppDynamicComment> commentWrapper = new QueryWrapper<>();
                commentWrapper.eq("dynamic_id", dynamicEntity.getId());
                commentWrapper.in("user_id", friendIdList);
                commentWrapper.and(Wrapper -> Wrapper.isNull("reply_user_id").or().in("reply_user_id", friendIdList));
                commentWrapper.orderByAsc("crt_time");
                commentList = commentService.list(commentWrapper);
                for (AppDynamicComment commentEntity : commentList) {
                    commentEntity.setUserName(commentEntity.getUserName());
                    commentEntity.setContent(CommonUtils.decodeNickname(commentEntity.getContent()));
                    if (commentEntity.getpId() != null)
                        commentEntity.setReplyUserName(commentEntity.getReplyUserName());
                }
                dynamicEntity.setCommentList(commentList);
            }
            dynamicList.add(dynamicEntity);
        }

        // 未读动态转为已读
        if (noReadTimelineList.size() > 0) timelineService.updateBatchById(noReadTimelineList);

        ret.put("totalPage", timelinePage.getPages());
        ret.put("totalCount", timelinePage.getSize());
        ret.put("dynamicList", dynamicList);

        return AjaxResult.ok(0, "", ret);
    }

    @PostMapping("releaseDynamic")
    @ApiOperation("发布动态")
    public AjaxResult releaseDynamic(@ApiParam("类型，0：纯文本，1：图片，2：视频") Integer type,
                                     @ApiParam("文本内容") String content,
                                     @ApiParam("图片json，['','']") String imgs,
                                     @ApiParam("视频封面") String videoCover,
                                     @ApiParam("一张图片其对应的宽高") String imgWidthHigh,
                                     @ApiParam("位置") String location,
                                     @ApiParam("提醒用户ids") String remindUserIds,
                                     @ApiParam("查看状态，0：公开，1：私密，2：部分人可见，3：部分不可见") @RequestParam(defaultValue = "0") Integer seeState, @ApiParam("可查看用户ids") String seeUserIds, @ApiParam("不能查看用户ids") String refuseUserIds) {
        if (type == null) {
            return AjaxResult.error(-1, "动态类型不能为空");
        }
        if (type == 0 && StringUtils.isBlank(content)) {
            return AjaxResult.error(-1, "发布内容不能为空");
        }
        if ((type == 1 || type == 2) && StringUtils.isBlank(imgs)) {
            return AjaxResult.error(-1, "图片/视频不能为空");
        }
        AppUser userEntity = userService.getById(getUserId());
        AppDynamic dynamicEntity = new AppDynamic();
        dynamicEntity.setCrtTime(new Date());
        dynamicEntity.setCreateTime(new Date());
        dynamicEntity.setUserId(getUserId());
        dynamicEntity.setUserName(userEntity.getUsername());
        dynamicEntity.setUserHeadImg(userEntity.getHeadImg());
        dynamicEntity.setType(type);
        dynamicEntity.setContent(CommonUtils.encodeNickname(content));
        dynamicEntity.setImgs(imgs);
        dynamicEntity.setVideoCover(videoCover);
        dynamicEntity.setImgWidthHigh(imgWidthHigh);
        dynamicEntity.setLocation(location);
        dynamicEntity.setRemindUserIds(remindUserIds);
        dynamicEntity.setSeeState(seeState);
        dynamicEntity.setSeeUserIds(seeUserIds);
        dynamicEntity.setRefuseUserIds(refuseUserIds);
        return dynamicService.releaseDynamic(dynamicEntity);
    }

    @DeleteMapping("removeDynamic")
    @ApiOperation("删除动态")
    public AjaxResult removeDynamic(@ApiParam("动态id") Long id) {
        dynamicService.deleteAppDynamicById(id);
        return AjaxResult.ok(0, "删除动态成功", null);
    }

    @PostMapping("likeDynamic")
    @ApiOperation("点赞/取消点赞动态")
    public AjaxResult likeDynamic(@ApiParam("动态id") Long id) {

        int count = likeService.countByDynamicIdAndUserId(id, getUserId());
        if (count == 0) {
            return likeService.addLikeDynamic(getUserId(), id);
        } else {
            return likeService.cancelLikeDynamic(getUserId(), id);
        }
    }

    @PostMapping("commentDynamic")
    @ApiOperation("评论动态")
    public AjaxResult commentDynamic(@ApiParam("动态id") Long id, @ApiParam("评论内容") String content) {
        return commentService.commentDynamic(getUserId(), id, content);
    }

    @PostMapping("replyComment")
    @ApiOperation("回复评论")
    public AjaxResult replyComment(@ApiParam("评论id") Long commentId, @ApiParam("评论内容") String content) {
        return commentService.replyComment(getUserId(), commentId, content);
    }

    @PostMapping("removeComment")
    @ApiOperation("删除评论")
    public AjaxResult removeComment(@ApiParam("评论id") Long commentId) {
        int count = commentService.countByCommentIdAndUserId(commentId, getUserId());
        if (count == 0) {
            return AjaxResult.error(-1, "只能删除自己的评论！");
        }
        return commentService.removeComment(commentId);
    }

    @PostMapping("getNoReadMsgCount")
    @ApiOperation("获取朋友圈未读消息条数")
    public AjaxResult getNoReadMsgCount() {
        AppDynamicMsg appDynamicMsg = new AppDynamicMsg();
        appDynamicMsg.setUserId(getUserId());
        appDynamicMsg.setMsgStatus(0);

        List<AppDynamicMsg> msgList = iAppDynamicMsgService.selectAppDynamicMsgList(appDynamicMsg);

        int count = 0;
        String headImg = "";
        if (msgList.size() > 0) {
            count = msgList.size();
            headImg = msgList.get(0).getFromUserHeadImg();
        }

        AppDynamicTimeline appDynamicTimeline = new AppDynamicTimeline();
        appDynamicTimeline.setUserId(getUserId());
        appDynamicTimeline.setIsRead(0);
        int dynamicCount = timelineService.countByUserIdAndIsRead(appDynamicTimeline);

        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("headImg", headImg);
        map.put("dynamicCount", dynamicCount);
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping("getMsgPage")
    @ApiOperation("获取朋友圈消息分页")
    public AjaxResult getMsgPage(@ApiParam("userId") Long userId,
                                 @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
                                 @ApiParam("条数") @RequestParam(defaultValue = "10") Integer limit) {

        QueryWrapper<AppDynamicMsg> queryWrapper = Wrappers.query();
        queryWrapper.eq("user_id", getUserId());
        Page<AppDynamicMsg> obj = iAppDynamicMsgService.page(new Page<>(page, limit), queryWrapper);

        List<AppDynamicMsg> list = obj.getRecords();

        for (AppDynamicMsg dynamicMsgEntity : list) {
            dynamicMsgEntity.setDynamicContent(CommonUtils.decodeNickname(dynamicMsgEntity.getDynamicContent()));
            dynamicMsgEntity.setFromUserName(CommonUtils.decodeNickname(dynamicMsgEntity.getFromUserName()));
            if (StringUtils.isNotBlank(dynamicMsgEntity.getContent()))
                dynamicMsgEntity.setContent(CommonUtils.decodeNickname(dynamicMsgEntity.getContent()));
            if (StringUtils.isNotBlank(dynamicMsgEntity.getReplyUserName()))
                dynamicMsgEntity.setReplyUserName(CommonUtils.decodeNickname(dynamicMsgEntity.getReplyUserName()));
        }

        // 将未读消息全部置为已读
        iAppDynamicMsgService.updateByUserIdAndMsgStatus(userId, 0);
        Map<String, Object> map = new HashMap<>();
        map.put("totalCount", obj.getTotal());
        map.put("totalPage", obj.getPages());
        map.put("list", list);
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping("emptyMsg")
    @ApiOperation("清空朋友圈消息")
    public AjaxResult emptyMsg() {
        iAppDynamicMsgService.removeByUserId(getUserId());
        return AjaxResult.ok(0, "清空成功", null);
    }

    @PostMapping("getSelfDynamicPage")
    @ApiOperation("获取单人用户动态分页")
    public AjaxResult getSelfDynamicPage(@ApiParam("userId") Long currentLoginUserId, @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page, @ApiParam("条数") @RequestParam(defaultValue = "6") Integer limit) {
        QueryWrapper<AppDynamicTimeline> queryWrapper = Wrappers.query();
        queryWrapper.eq("user_id", currentLoginUserId);
        queryWrapper.eq("is_own", 1);
        Page<AppDynamicTimeline> obj = timelineService.page(new Page<>(page, limit), queryWrapper);
        List<AppDynamicTimeline> list = obj.getRecords();

        boolean isLookLoginSelf = false;
        if (currentLoginUserId.equals(getUserId())) {
            isLookLoginSelf = true;
        }
        /*
         * 获取好友idList
         */
        List<Long> friendIdList = Lists.newArrayList();
        if (!isLookLoginSelf) {
            // 用户与好友设置的朋友圈权限
            AppUserRelation appUserRelation = new AppUserRelation();
            appUserRelation.setUserId(currentLoginUserId);
            appUserRelation.setSelfState(0);
            appUserRelation.setSelfIsBeLooked(0);
            appUserRelation.setOtherState(0);
            appUserRelation.setOtherIsLook(0);
            // 动态的可见权限
            // 用户与好友设置的朋友圈权限
            friendIdList = userRelationService.selectAppUserIds(appUserRelation);
            friendIdList.add(currentLoginUserId);
        }

        /*
         * 获取分页对应动态详情
         */
        List<AppDynamic> dynamicList = Lists.newArrayList();
        AppDynamic dynamicEntity;
        AppDynamicTimeline timelineEntity;
        List<AppDynamicLike> likeList;
        List<AppDynamicComment> commentList;
        for (int i = 0; i < list.size(); i++) {
            timelineEntity = list.get(i);
            dynamicEntity = dynamicService.selectAppDynamicById(timelineEntity.getDynamicId());

            dynamicEntity.setUserName(dynamicEntity.getUserName());
            dynamicEntity.setContent(CommonUtils.decodeNickname(dynamicEntity.getContent()));// 当前用户是否点赞
            dynamicEntity.setIsLike(0);
            if (dynamicEntity.getLikeCount() > 0) {
                // 获取点赞列表
                AppDynamicLike appDynamicLike = new AppDynamicLike();
                appDynamicLike.setDynamicId(dynamicEntity.getId());
                if (!isLookLoginSelf) {
                    appDynamicLike.setUserIds(friendIdList);
                }
                likeList = likeService.selectAppDynamicLikeList(appDynamicLike);

                for (AppDynamicLike likeEntity : likeList) {
                    likeEntity.setUserName(likeEntity.getUserName());
                    if (likeEntity.getUserId().equals(currentLoginUserId)) dynamicEntity.setIsLike(1);
                }
                dynamicEntity.setLikeList(likeList);
            }
            if (dynamicEntity.getCommentCount() > 0) {
                // 获取评论列表

                AppDynamicComment appDynamicComment = new AppDynamicComment();
                appDynamicComment.setDynamicId(dynamicEntity.getId());
                if (!isLookLoginSelf) {
                    appDynamicComment.setUserIds(friendIdList);
                }

                commentList = commentService.selectAppDynamicCommentList(appDynamicComment);
                for (AppDynamicComment commentEntity : commentList) {
                    commentEntity.setUserName(commentEntity.getUserName());
                    commentEntity.setContent(CommonUtils.decodeNickname(commentEntity.getContent()));
                    if (commentEntity.getpId() != null)
                        commentEntity.setReplyUserName(commentEntity.getReplyUserName());
                }
                dynamicEntity.setCommentList(commentList);
            }
            dynamicList.add(dynamicEntity);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("totalCount", obj.getTotal());
        map.put("totalPage", obj.getPages());
        map.put("dynamicList", dynamicList);
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping("getDynamicInfo")
    @ApiOperation("获取动态详情")
    public AjaxResult getDynamicInfo(@ApiParam("动态id") @RequestParam Long dynamicId) {
        AppDynamic dynamicEntity = dynamicService.selectAppDynamicById(dynamicId);
        dynamicEntity.setUserName(CommonUtils.decodeNickname(dynamicEntity.getUserName()));
        dynamicEntity.setContent(CommonUtils.decodeNickname(dynamicEntity.getContent()));
        // 当前用户是否点赞
        dynamicEntity.setIsLike(0);
        if (dynamicEntity.getLikeCount() > 0) {
            // 获取点赞列表
            AppDynamicLike appDynamicLike = new AppDynamicLike();
            appDynamicLike.setDynamicId(dynamicEntity.getId());

            List<AppDynamicLike> likeList = likeService.selectAppDynamicLikeList(appDynamicLike);
            for (AppDynamicLike likeEntity : likeList) {
                likeEntity.setUserName(CommonUtils.decodeNickname(likeEntity.getUserName()));
                if (likeEntity.getUserId().equals(dynamicEntity.getUserId())) dynamicEntity.setIsLike(1);
            }
            dynamicEntity.setLikeList(likeList);
        }
        if (dynamicEntity.getCommentCount() > 0) {
            // 获取评论列表
            AppDynamicComment appDynamicComment = new AppDynamicComment();
            appDynamicComment.setDynamicId(dynamicEntity.getId());

            List<AppDynamicComment> commentList = commentService.selectAppDynamicCommentList2(appDynamicComment);

            List<AppDynamicComment> sortCommentList = Lists.newArrayList();
            //            sortComment(sortCommentList, commentList, null);
            for (AppDynamicComment commentEntity : commentList) {
                commentEntity.setUserName(CommonUtils.decodeNickname(commentEntity.getUserName()));
                commentEntity.setContent(CommonUtils.decodeNickname(commentEntity.getContent()));
                if (commentEntity.getpId() != null)
                    commentEntity.setReplyUserName(CommonUtils.decodeNickname(commentEntity.getReplyUserName()));
            }
            dynamicEntity.setCommentList(sortCommentList);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("dynamicEntity", dynamicEntity);
        return AjaxResult.ok(0, "", map);
    }

    /**
     * 递归父子排序评论
     *
     * @param sortCommentList
     * @param commentList
     */
    public void sortComment(List<AppDynamicComment> sortCommentList, List<AppDynamicComment> commentList, Long pId) {
        for (AppDynamicComment commentEntity : commentList) {
            if ((pId == null && commentEntity.getpId() == null) || (pId != null && pId.equals(commentEntity.getpId()))) {
                sortCommentList.add(commentEntity);
                sortComment(sortCommentList, commentList, commentEntity.getId());
            }
        }
    }

    @PostMapping("getPermissionUserList")
    @ApiOperation("获取动态受权限用户列表数据")
    public AjaxResult getPermissionUserList(@ApiParam("动态id") @RequestParam Long dynamicId) {
        AppDynamic dynamicEntity = dynamicService.selectAppDynamicById(dynamicId);
//        Assert.isNull(dynamicEntity, "动态id不存在！");
        if (dynamicEntity == null) {
            return AjaxResult.error(-1, "动态id不存在");
        }
        if (dynamicEntity.getSeeState() < 2) {
            return AjaxResult.error(-1, "动态没有受权限用户");
        }

        List<AppUser> userList = Lists.newArrayList();
        String permissionUserIds = dynamicEntity.getSeeState() == 2 ? dynamicEntity.getSeeUserIds() : dynamicEntity.getRefuseUserIds();
        if (StringUtils.isNotBlank(permissionUserIds)) {
            userList = userService.listByUserIds(Arrays.asList(dynamicEntity.getSeeUserIds().split(",")));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userList", userList);

        return AjaxResult.ok(0, "", map);
    }

    /**
     * 上传朋友圈动态图片、短视频
     *
     * @param request
     * @return
     */
    @PostMapping("uploadDynamicFile")
    @ApiOperation("上传朋友圈动态图片、短视频。类型参数：type，0：图片；1：短视频")
    public AjaxResult uploadDynamicFile(HttpServletRequest request) throws Exception {
        // 类型，0：图片；1：短视频
        String type = request.getParameter("type");
        if (StringUtils.isBlank(type) || (!type.equals("0") && !type.equals("1"))) {
            throw new RRException("文件类型错误");
        }
        // 上传文件list
        List<MultipartFile> fileList = Lists.newArrayList();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multipartRequest.getFileNames();

        while (iter.hasNext()) {
            if (type.equals("0") && fileList.size() == 9) throw new RRException("图片最多只能上传9张");
            else if (type.equals("1") && fileList.size() == 1) throw new RRException("短视频最多只能上传一份");
            MultipartFile file = multipartRequest.getFile(iter.next());
            if (file.isEmpty()) throw new RRException("文件不能为空");
            // 文件大小，1M = 1048576
            Long fileSize = file.getSize();
            if (fileSize > 10485760) throw new RRException("上传失败：文件大小不能超过10M");
            fileList.add(file);
        }

        JSONArray imgs = new JSONArray();
        String videoCover = "";
        JSONObject imgWidthHigh = new JSONObject();
        for (int i = 0; i < fileList.size(); i++) {
            String url = "";
            if (type.equals("0")) {
                url = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), fileList.get(i), MimeTypeUtils.IMAGE_EXTENSION);
            }

            if (type.equals("1")) {
                url = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), fileList.get(i), MimeTypeUtils.VIDEO_EXTENSION);
            }
            // 仅上传一张图片时，获取图片对应的宽高
            if (type.equals("0") && fileList.size() == 1) {
                Map<String, Integer> imageInfo = FilesUploadUtils.getImageInfo(FilesUploadUtils.multipartFileToFile(fileList.get(0)));
                imgWidthHigh.put("width", imageInfo.get("width"));
                imgWidthHigh.put("height", imageInfo.get("height"));
            }

            /*
             * 上传视频，若不是mp4格式，进行转码
             */
            if (type.equals("1")) {
                File file = MultipartFileToFile(fileList.get(0));
                Encoder encoder = new Encoder();
                try (FileInputStream fis = new FileInputStream(file)) {
                    MultimediaInfo m = encoder.getInfo(file);
                    imgWidthHigh.put("width", m.getVideo().getSize().getWidth());
                    imgWidthHigh.put("height", m.getVideo().getSize().getWidth());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            imgs.add(url);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("imgs", imgs.toJSONString());
        map.put("videoCover", videoCover);
        map.put("imgWidthHigh", imgWidthHigh.toJSONString());
        return AjaxResult.ok(0, "", map);
    }

    /**
     * 将MultipartFile转换为File
     *
     * @param multiFile 传入的文件
     * @return 出参
     */
    private File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        //时间戳+6位随机数
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String date2 = sdf2.format(new Date());
        String random = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
        String preName = date2 + random;

        try {
            File file = File.createTempFile(fileName + preName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param second 秒
     * @description: 秒转换为时分秒 HH:mm:ss 格式 仅当小时数大于0时 展示HH
     * @return: {@link String}
     */
    public static String second2Time(Long second) {
        if (second == null || second < 0) {
            return "00:00";
        }

        long h = second / 3600;
        long m = (second % 3600) / 60;
        long s = second % 60;
        String str = "";
        if (h > 0) {
            str = (h < 10 ? ("0" + h) : h) + ":";
        }
        str += (m < 10 ? ("0" + m) : m) + ":";
        str += (s < 10 ? ("0" + s) : s);
        return str;
    }

}
